package com.yiyi.credit.manage.sso.common.utils;

import org.codehaus.jackson.JsonParser.Feature;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.type.JavaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

public class JsonUtil {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    protected static final ObjectMapper MAPPER = new CustomerObjectMapper();

    static {
        MAPPER.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        MAPPER.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        MAPPER.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    }

    public static <T> String toJson(T t) {
        logger.info("");
        try {
            return MAPPER.writeValueAsString(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T toObject(String str, Class<T> c) {
        T response = null;
        if (str != null) {
            try {
                response = (T) MAPPER.readValue(str, c);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    public static JavaType getMapCollectionType(Class<?>... elementClasses) {
        return MAPPER.getTypeFactory().constructParametricType(HashMap.class, elementClasses);
    }


}